package zouran.shounewsspringboot.controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zouran.shounewsspringboot.entity.MyConfig;
import zouran.shounewsspringboot.entity.ResultMap;
import zouran.shounewsspringboot.service.NewsService;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author zouran
 * createDate：2023/5/31  21:28
 */
@CrossOrigin
@RestController
@RequestMapping("/news")
public class NewsController {
    private final MyConfig myConfig;
    private final ResultMap<Object> resultMap;
    private final NewsService newsService;
    private final HttpServletResponse response;
    public NewsController(MyConfig myConfig, ResultMap<Object> resultMap, NewsService newsService, HttpServletResponse response) {
        this.myConfig = myConfig;
        this.resultMap = resultMap;
        this.newsService = newsService;
        this.response = response;
    }

    /**
     * @param author 作者名
     * @return 所有新闻
     */
    @RequestMapping("/getAllNewsByAuthor")
    public ResultMap<Object> getAllNewsByAuthor(@Param("author") String author){
        return resultMap.success(newsService.getAllNewsByAuthor(author));
    }

    /**
     * @return 总的数量
     */
    @RequestMapping("/getAllCount")
    public ResultMap<Object> getAllCount() {
        return resultMap.success(newsService.getAllCount());
    }
    /**
     * @param url 文章地址
     * @return 是否添加成功
     */
    @RequestMapping("/addNews/wechat")
    public ResultMap<Object> addWechatNews(@Param("url") String url) throws Exception{
        return resultMap.success(newsService.addWechatNews(url));
    }

    /**
     * @param url 图片访问地址
     */
    @RequestMapping("/img")
    public void getImg(@Param("url") String url) throws IOException {
        String storage= myConfig.getFilePath()+url;
        File file=new File(storage);
        InputStream inputStream;
        if(!file.exists()){
            inputStream=Files.newInputStream(Paths.get(myConfig.getFilePath() + "error.png"));
        }
        else {
            inputStream = Files.newInputStream(Paths.get(storage));
        }
        OutputStream outputStream=response.getOutputStream();
        int len;
        byte[] bytes=new byte[1024];
        while ((len= inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
    }
}
